package com.chandon.juc.threadPool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * @author Chandon
 */

public class TestWorkJoinPool {
	public static void main(String[] args) throws ExecutionException, InterruptedException {

		ForkJoinPool pool = new ForkJoinPool(10);

		int[] array = IntStream.rangeClosed(0, 100).toArray();

		SumRecursiveTask task = new SumRecursiveTask(0, array.length - 1, array, 20);

		ForkJoinTask<Integer> result = pool.submit(task);

		System.out.println(result.get());

	}


}

class SumResivetaskA extends RecursiveTask<Integer> {

	private int start, end, stride;
	private int[] arr;

	public SumResivetaskA(int start, int end, int stride, int[] arr) {
		this.start = start;
		this.end = end;
		this.stride = stride;
		this.arr = arr;
	}

	@Override
	protected Integer compute() {

		int sum = 0;

		if (end - start > stride) {

			SumResivetaskA taskLeft = new SumResivetaskA(start, (end - start) / 2, stride, arr);
			SumResivetaskA taskRight = new SumResivetaskA((end - start) / 2 + 1, end, stride, arr);

			taskLeft.fork();
			taskRight.fork();

			return taskLeft.join() + taskRight.join();
		}

		for (int i = start; i < end; i++) {
			sum += arr[i];
		}

		return sum;
	}
}